<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="产品编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品性质" prop="nature">
        <el-select
          v-model="queryParams.nature"
          placeholder="请选择产品性质"
          clearable
        >
          <el-option
            v-for="dict in dict.type.zc_product_nature"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品品种" prop="breed">
        <el-select
          v-model="queryParams.breed"
          placeholder="请选择产品品种"
          clearable
        >
          <el-option
            v-for="dict in dict.type.zc_breed"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品颜色" prop="color">
        <el-input
          v-model="queryParams.color"
          placeholder="请输入产品颜色"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择产品状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.zc_plan_code"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sales:product:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sales:product:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sales:product:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sales:product:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="productList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编码" align="center" prop="code" />
      <el-table-column label="产品名称" align="center" prop="name" />
      <el-table-column
        label="原料品类"
        align="center"
        key="stockName"
        prop="stock.stockName"
      />
      <el-table-column
        label="类别工序"
        align="center"
        key="processName"
        prop="process.processName"
      />
      <el-table-column label="产品规格" align="center" prop="specificationsId">
        <template slot-scope="scope">  
      <!-- 使用 scope.row 来访问当前行的数据 -->  
      <span>{{ getSpecString(scope.row.specificationsId) }}</span>  
    </template>
      </el-table-column>
      <el-table-column label="产品性质" align="center" prop="nature">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.zc_product_nature"
            :value="scope.row.nature"
          />
        </template>
      </el-table-column>
      <el-table-column label="产品品种" align="center" prop="breed">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zc_breed" :value="scope.row.breed" />
        </template>
      </el-table-column>
      <el-table-column label="产品颜色" align="center" prop="color">
        <!-- 颜色显示 -->
        <template slot-scope="scope">
          <el-button :style="{ backgroundColor: scope.row.color }"></el-button>
          <!-- <span >{scope.row.color}</span> -->
        </template>
      </el-table-column>
      <el-table-column label="产品状态" align="center" prop="status">
        <!-- <template slot-scope="scope">
          <dict-tag :options="dict.type.zc_plan_code" :value="scope.row.status"/>
        </template> -->
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sales:product:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sales:product:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="16">
            <el-form-item label="原料品类" prop="stockId">
              <!-- :disable-branch-nodes="true" 只能选中最小的叶子节点 -->
              <!-- :show-count="true" 显示 字节的个数 -->
              <treeselect
                v-model="form.stockId"
                :options="stockOptions"
                :show-count="true"
                :disable-branch-nodes="true"
                placeholder="请选择产品所用的原料品类"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="类别工序" prop="processId">
              <!-- :disable-branch-nodes="true" 只能选中最小的叶子节点 -->
              <!-- :show-count="true" 显示 字节的个数 -->
              <treeselect
                v-model="form.processId"
                :options="processOptions"
                :show-count="true"
                :disable-branch-nodes="true"
                placeholder="请选择产品的类别工序"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="产品规格" prop="specificationsId">
              <el-select
                v-model="form.specificationsId"
                placeholder="请选择产品规格"
              >
                <el-option
                  v-for="item in specOptions"
                  :key="item.specificationsId"
                  :label="item.specString"
                  :value="item.specificationsId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="产品性质" prop="nature">
          <el-select v-model="form.nature" placeholder="请选择产品性质">
            <el-option
              v-for="dict in dict.type.zc_product_nature"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品品种" prop="breed">
          <el-select v-model="form.breed" placeholder="请选择产品品种">
            <el-option
              v-for="dict in dict.type.zc_breed"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="16">
            <el-form-item label="产品颜色" prop="color">
              <!-- <el-input v-model="form.color" placeholder="请输入产品颜色" /> -->
              <el-color-picker
                v-model="form.color"
                placeholder="请输入产品颜色"
              ></el-color-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="产品状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.zc_plan_code"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProduct,
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
  stockTreeSelect,
  processTreeSelect,
  changeUserStatus,
  specListSelect,
} from "@/api/sales/product";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Product",
  dicts: ["zc_breed", "zc_plan_code", "zc_product_nature"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        nature: null,
        breed: null,
        color: null,
        status: null,
        stockId: null,
        processId: null,
        specificationsId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nature: [
          { required: true, message: "产品性质不能为空", trigger: "change" },
        ],
        breed: [
          { required: true, message: "产品品种不能为空", trigger: "change" },
        ],
        status: [
          { required: true, message: "产品状态不能为空", trigger: "change" },
        ],
        stockId: [
          { required: true, message: "原料品类不能为空", trigger: "change" },
        ],
        processId: [
          { required: true, message: "类别工序不能为空", trigger: "change" },
        ],
        specificationsId: [
          { required: true, message: "产品规格不能为空", trigger: "change" },
        ],
      },
      // 原料品类树选项
      stockOptions: undefined,
      // 原料品类名称
      stockName: undefined,
      // 类别工序树选项
      processOptions: undefined,
      // 类别工序名称
      processName: undefined,
      // 产品规格选项
      specOptions: undefined,
      specStrings: [],
    };
  },
  // watch: {
  //   // 根据名称筛选原料品类树
  //   stockName(val) {
  //     this.$refs.tree.filter(val);
  //   }
  // },
  created() {
    this.getList();
    this.getStockTree();
    this.getProcessTree();
    this.getSpec();
  },
  methods: {
    getSpecString(specificationsId) {  
    // 直接从 specStrings 对象中通过 specificationsId 查找 specString  
    return this.specStrings[specificationsId] || '未知规格';  
  },  
    // 查询产品规格列表
    getSpec() {
      specListSelect().then((response) => {
        this.specOptions = response.data;
        this.specOptions.forEach((item) => {
          const wide = item.wide;
          const weight = item.weight;
          const specString = `幅宽${wide},克重${weight}`;
          // 在 item 对象中添加 specString 字段
          item.specString = specString;
          // 在 specStrings 对象中建立 specificationsId 和 specString 的映射  
      this.$set(this.specStrings, item.specificationsId, specString);  
        });
      });
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "禁用";
      this.$modal
        .confirm('确认要"' + text + '"该工序类别吗？')
        .then(function () {
          return changeUserStatus(row.productId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 查询原料品类下拉树结构 */
    getStockTree() {
      stockTreeSelect().then((response) => {
        this.stockOptions = response.data;
      });
    },
    /** 查询类别工序下拉树结构 */
    getProcessTree() {
      processTreeSelect().then((response) => {
        this.processOptions = response.data;
      });
    },
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then((response) => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        stockId: null,
        processId: null,
        specificationsId: null,
        code: null,
        name: null,
        nature: null,
        breed: null,
        // 默认颜色白色
        color: "#FFFFFF",
        // 默认状态为启动
        status: "0",
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        del: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.stockId = null;
      this.queryParams.processId = null;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.productId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids;
      getProduct(productId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.productId != null) {
            updateProduct(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal
        .confirm('是否确认删除产品编号为"' + productIds + '"的数据项？')
        .then(function () {
          return delProduct(productIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "sales/product/export",
        {
          ...this.queryParams,
        },
        `product_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
